/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package crypto

import (
	"errors"
	"hash"
)

var Undecryptable = errors.New("undecryptable input")

type config interface {
	Secret() []byte
}

// https://nodejs.org/api/crypto.html#crypto_crypto_createdecipher_algorithm_password_options
// openssl/evp.h - EVP_BytesToKey
func bytesToKey(hashAlgorithm func() hash.Hash, secret, salt []byte, iteration int, keySize, ivSize int) (key, iv []byte) {
	h := hashAlgorithm()
	var d, result []byte
	sum := make([]byte, 0, h.Size())
	for len(result) < keySize+ivSize {
		h.Reset()
		h.Write(d)
		h.Write(secret)
		h.Write(salt)
		sum = h.Sum(sum[:0])
		for j := 1; j < iteration; j++ {
			h.Reset()
			h.Write(sum)
			sum = h.Sum(sum[:0])
		}
		d = append(d[:0], sum...)
		result = append(result, d...)
	}
	return result[:keySize], result[keySize : keySize+ivSize]
}
